<script setup lang='ts'>
import type { PlusColumn } from 'plus-pro-components'
import { labelShow, sortEnableList, useLabelAddOrUpdate, useLabelShow, useSortEnableList } from '@fl/api/advertising-api/flash-management'
import type { labelEditParam } from '@fl/api/advertising-api/model/flash-management-types'
import { SubmitBtn } from '@fl/components'
import { cloneDeep } from 'lodash-es'

import { useCity } from '../hooks/use-city'

const props = withDefaults(defineProps<{
    sortOptions?: any
}>(), {
    sortOptions: [],
})

const visible = defineModel<boolean>('visible', { required: true })
const id = defineModel<string>('id', { required: true })
const { cityOptions, queryCityList } = useCity()
onMounted(() => {
    // 详情
    const { data: detail } = useLabelShow(id)
    if (detail.value) {
        state.value = cloneDeep(detail.value)
        if (state.value.cityCode) {
            const classList = classifyList.value.filter((item) => {
                return item.cityCode === state.value.cityCode
            })
            classifyOptions.value = classList
        }
        else {
            classifyOptions.value = []
        }
    }
})
const classifyList = ref([])
const classifyOptions = ref([])
const sortList = ref([])
function getClassifyList() {
    sortEnableList().then((res) => {
        sortList.value = res
        if (sortList.value) {
            const sortTempOptions = cloneDeep(sortList.value).reduce((pre: any, cur: any) => {
                cur.value = cur.id
                cur.label = cur.classifyName
                pre.push(cur)
                return pre
            }, [])
            classifyList.value = cloneDeep(sortTempOptions)
        }
    })
}

function cityChange(cityCode) {
    state.value.classifyId = ''
    if (cityCode) {
        const classList = classifyList.value.filter((item) => {
            return item.cityCode === cityCode
        })

        const cityItem = cityOptions.value.find((item) => {
            return item.value === cityCode
        })
        if (cityItem) {
            state.value.cityName = cityItem.label
        }
        classifyOptions.value = classList
    }
    else {
        classifyOptions.value = []
    }
}

const formRef = ref()
const title = ref('添加快讯标签')

const initialState = {
    labelName: '',
    cityName: '',
    cityCode: '',
    classifyId: '',
}
const state = ref<labelEditParam>(cloneDeep(initialState))

watch(visible, (newValue, oldValue) => {
    if (newValue) {
        queryCityList()
        getClassifyList()
    }

    if (id.value) {
        title.value = '编辑快讯标签'
        if (newValue) {
            labelShow(id.value).then((res) => {
                state.value = cloneDeep(res)
                if (state.value.cityCode) {
                    const classList = classifyList.value.filter((item) => {
                        return item.cityCode === state.value.cityCode
                    })
                    classifyOptions.value = classList
                }
                else {
                    classifyOptions.value = []
                }
            })
        }
    }
    else {
        title.value = '新增快讯标签'
    }
}, { deep: true, immediate: true })

// 提交表单
const { isPending, mutate } = useLabelAddOrUpdate()

// 提交
async function submit() {
    const valid = await formRef.value.formInstance.validate()
    if (valid) {
        const target = classifyList.value.find((item) => {
            return item.value == state.value.classifyId
        })
        const params = {
            id: id.value ?? '',
            ...unref(state),
            classifyName: target.label,
        }
        console.log('params', params)
        mutate(params, {
            onSuccess: () => {
                ElMessage.success('操作成功')
                reset()
            },
        })
    }
}

function cancel() {
    reset()
}

function reset() {
    visible.value = false
    state.value = cloneDeep(initialState)
    formRef.value.formInstance.resetFields()
    id.value = ''
}

const columns: PlusColumn[] = [
    {
        label: '快讯标签',
        fieldProps: {
            maxlength: 10,
        },
        prop: 'labelName',
    },
    {
        label: '所属城市',
        fieldProps: {
            maxlength: 10,
        },
        prop: 'cityCode',
        valueType: 'select',
    },
    {
        label: '关联分类',
        prop: 'classifyId',
        valueType: 'select',
    },
]

const rules = {
    labelName: [
        {
            message: '请输入标签名称',
            required: true,
        },
    ],
    cityCode: [
        {
            message: '请选择所属城市',
            required: true,
        },
    ],
    classifyId: [
        {
            message: '请选择关联分类',
            required: true,
        },
    ],
}
</script>

<template>
    <PlusDialog v-model="visible"
                :title="title"
                width="500"
                close-on-press-escape
                :has-footer="false"
                destroy-on-close
                @cancel="cancel"
                @closed="reset"
    >
        <ElSkeleton v-if="isLoading"
                    animated
                    class="mt-20"
        />

        <template v-else>
            <div class="mt-20">
                <PlusForm ref="formRef"
                          v-model="state"
                          :columns="columns"
                          :label-width="120"
                          :rules="rules"
                          :has-footer="false"
                          :row-props="{ gutter: 20 }"
                >
                    <template #plus-field-cityCode>
                        <el-select v-model="state.cityCode"
                                   placeholder="请选择所属城市2"
                                   clearable
                                   @change="cityChange"
                        >
                            <el-option v-for="item in cityOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>

                    <template #plus-field-classifyId>
                        <el-select v-model="state.classifyId"
                                   placeholder="请选择关联分类"
                        >
                            <el-option v-for="item in classifyOptions"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </template>
                </PlusForm>
            </div>

            <div class="mx-auto mt20 flex justify-center">
                <el-button @click="cancel">
                    取消
                </el-button>

                <SubmitBtn type="primary"
                           :loading="isPending"
                           @click="submit"
                >
                    提交
                </SubmitBtn>
            </div>
        </template>
    </PlusDialog>
</template>
